#include "../thirdparty/Simple-Web-Server/client_http.hpp"
#include "../thirdparty/Simple-Web-Server/server_http.hpp"
#include <future>
#include <thread>
#include <chrono>

#include <opencv2/opencv.hpp>

#define BOOST_SPIRIT_THREADSAFE
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/signals2.hpp>

// Added for the default_resource example
#include <algorithm>
#include <boost/filesystem.hpp>
#include <fstream>
#include <vector>
#ifdef HAVE_OPENSSL
#include "crypto.hpp"
#endif

#include "spdlog/spdlog.h"
#include "lib/webserver/web_server.h"
#include "lib/service/ai_service.h"
#include "lib/controller/ai_controller.h"
#include "lib/data/data_store.h"

using namespace ai::facial_recognition;
using namespace std;

static volatile sig_atomic_t run = 1;

static void sigterm(int sig) {
  std::cout << "Signal received: " + std::to_string(sig) << std::endl;
  run = 0;
}


int main() {
  spdlog::set_level(spdlog::level::debug); // Set global log level to debug
  spdlog::info("Demo is starting......");

  signal(SIGINT, sigterm);
  signal(SIGTERM, sigterm);

  AIController ai_controller;

  // Initialize web server with port 8080
  WebServer web_server{8080};
  // 初始化服务
  AIService ai_service{};

  DataStore data_store;

  ai_service.set_data_store(&data_store);

  web_server.subscribeRequest([&](RequestMessagePtr msg){ ai_controller.onWebRequest(msg); });
  ai_controller.subscribeRequest([&](RequestMessagePtr msg){ ai_service.onWebRequest(msg); });

  spdlog::info("Demo(web_server) is starting......");
  ai_service.start();
  web_server.start();

  spdlog::info("Demo has started.");

  while (run)
  {
    std::this_thread::sleep_for(std::chrono::seconds(1));
  }

  spdlog::info("Demo is terminating......");

  web_server.stop();
  ai_service.stop();

  spdlog::info("Web_server stopped.");
  spdlog::info("Application terminated.");
}

